jQuery(function() {

    WebUploader.Uploader.register({
        'before-send-file': 'getmd5'
    }, {
        getmd5: function( file ) {
            var me = this,
                owner = this.owner,
                server = me.options.server,
                deferred = WebUploader.Deferred();

            owner.md5File( file.source )
            	.fail(function() {deferred.reject();})
                .then(function( md5 ) {
                	me.options.formData.md5=md5;
                	deferred.resolve();
                });
            return deferred.promise();
        }
    });
    var $ = jQuery,    // just in case. Make sure it's not an other libaray.

        $wrap3 = $('#uploader3'),

        // 图片容器
        // $queue = $('<ul class="filelist"></ul>')
        //     .appendTo( $wrap.find('.queueList') ),
        $queue3=$wrap3.find('.queueList3').find('.filelist3');
        // 状态栏，包括进度和控制按钮
        $statusBar3 = $wrap3.find('.statusBar3'),

        // 文件总体选择信息。
        $info3 = $statusBar3.find('.info3'),

        // 上传按钮
        $upload3 = $wrap3.find('.uploadBtn3'),

        // 没选择文件之前的内容。
        $placeHolder3 = $wrap3.find('.placeholder3'),

        // 总体进度条
        $progress3 = $statusBar3.find('.progress3').hide(),

        // 添加的文件数量
        fileCount3 = 0,

        // 添加的文件总大小
        fileSize3 = 0,

        // 优化retina, 在retina下这个值是2
        ratio3 = window.devicePixelRatio || 1,

        // 缩略图大小
        thumbnailWidth3 = 110 * ratio,
        thumbnailHeight3 = 110 * ratio,

        // 可能有pedding, ready, uploading, confirm, done.
        state3 = 'pedding',

        // 所有文件的进度信息，key为file id
        percentages3 = {},

        supportTransition3 = (function(){
            var s = document.createElement('p').style,
                r = 'transition' in s ||
                      'WebkitTransition' in s ||
                      'MozTransition' in s ||
                      'msTransition' in s ||
                      'OTransition' in s;
            s = null;
            return r;
        })(),

        // WebUploader实例
         uploader2;

    if ( !WebUploader.Uploader.support() ) {
        alert( 'Web Uploader 不支持您的浏览器！如果你使用的是IE浏览器，请尝试升级 flash 播放器');
        throw new Error( 'WebUploader does not support the browser you are using.' );
    }

    // 实例化
    var uploader2 = WebUploader.create({
        pick: {
            id: '#selectImgesBut',
            label: '点击选择'
        },
        dnd: '#uploader3 .queueList3',
        paste: document.body,
        accept: {
            title: 'Images',
            extensions: 'gif,jpg,jpeg,bmp,png',
            //mimeTypes: 'image/*'
            mimeTypes: 'image/jpg,image/jpeg,image/png'//解决谷歌打开文件选择慢的问题
        },
        // swf文件路径
        swf: '../assets/libs/webuploader/Uploader.swf',
        disableGlobalDnd: true,
        chunked: true,
        server: serverUrl2,
        fileNumLimit: 300,
        fileSizeLimit: 20 * 1024 * 1024,
        fileSingleSizeLimit: 5 * 1024 * 1024
    });

    // 添加“添加文件”的按钮，
    uploader2.addButton({
        id: '#filePicker3',
        label: '继续添加'
    });

    // 文件上传成功，给item添加成功class, 用样式标记上传成功。
    uploader2.on('uploadSuccess', function(file,response) {
        $( '#'+file.id ).find(".hiddenInput3").val(response.fileId);
    });


    // 当有文件添加进来时执行，负责view的创建
    function addFile3( file ) {
        var $li3 = $( '<li id="' + file.id + '">' +
                '<input type="hidden" class="hiddenInput3" name="detailIds" value=""/>'+
                '<p class="title">' + file.name + '</p>' +
                '<p class="imgWrap"></p>'+
                '<p class="progress"><span></span></p>' +
                '</li>' ),

            $btns3 = $('<div class="file-panel">' +
                '<span class="cancel">删除</span>' +
                // '<span class="rotateRight">向右旋转</span>' +
                // '<span class="rotateLeft">向左旋转</span>
                '</div>').appendTo( $li3 ),
            $prgress3 = $li3.find('p.progress span'),
            $wrap3 = $li3.find( 'p.imgWrap' ),
            $info3 = $('<p class="error"></p>'),

            showError3 = function( code ) {
                switch( code ) {
                    case 'exceed_size':
                        text = '文件大小超出';
                        break;

                    case 'interrupt':
                        text = '上传暂停';
                        break;

                    default:
                        text = '上传失败，请重试';
                        break;
                }

                $info3.text( text ).appendTo( $li3 );
            };

        if ( file.getStatus() === 'invalid' ) {
            showError3( file.statusText );
        } else {
            // @todo lazyload
            $wrap3.text( '预览中' );
            uploader2.makeThumb( file, function( error, src ) {
                if ( error ) {
                    $wrap3.text( '不能预览' );
                    return;
                }

                var img = $('<img src="'+src+'">');
                $wrap3.empty().append( img );
            }, thumbnailWidth3, thumbnailHeight3 );

            percentages3[ file.id ] = [ file.size, 0 ];
            file.rotation = 0;
        }

        file.on('statuschange', function( cur, prev ) {
            if ( prev === 'progress' ) {
                $prgress3.hide().width(0);
            } else if ( prev === 'queued' ) {
                $li3.off( 'mouseenter mouseleave' );
                $btns3.remove();
            }

            // 成功
            if ( cur === 'error' || cur === 'invalid' ) {
                console.log( file.statusText);
                showError3( file.statusText );
                percentages3[ file.id ][ 1 ] = 1;
            } else if ( cur === 'interrupt' ) {
                showError3( 'interrupt' );
            } else if ( cur === 'queued' ) {
                percentages3[ file.id ][ 1 ] = 0;
            } else if ( cur === 'progress' ) {
                $info3.remove();
                $prgress3.css('display', 'block');
            } else if ( cur === 'complete' ) {
                $li3.append( '<span class="success"></span>' );
            }

            $li3.removeClass( 'state-' + prev ).addClass( 'state-' + cur );
        });

        $li3.on( 'mouseenter', function() {
            $btns3.stop().animate({height: 30});
        });

        $li3.on( 'mouseleave', function() {
            $btns3.stop().animate({height: 0});
        });

        $btns3.on( 'click', 'span', function() {
            var index = $(this).index(),
                deg;

            switch ( index ) {
                case 0:
                    uploader2.removeFile( file );
                    return;

                case 1:
                    file.rotation += 90;
                    break;

                case 2:
                    file.rotation -= 90;
                    break;
            }

            if ( supportTransition ) {
                deg = 'rotate(' + file.rotation + 'deg)';
                $wrap3.css({
                    '-webkit-transform': deg,
                    '-mos-transform': deg,
                    '-o-transform': deg,
                    'transform': deg
                });
            } else {
                $wrap3.css( 'filter', 'progid:DXImageTransform.Microsoft.BasicImage(rotation='+ (~~((file.rotation/90)%4 + 4)%4) +')');
            }
        });
        $li3.appendTo( $queue3 );
    }

    // 负责view的销毁
    function removeFile3( file ) {
        var $li = $('#'+file.id);
        delete percentages3[ file.id ];
        updateTotalProgress3();
        $li.off().find('.file-panel').off().end().remove();
    }

    function updateTotalProgress3() {
        var loaded = 0,
            total = 0,
            spans = $progress3.children(),
            percent;

        $.each( percentages3, function( k, v ) {
            total += v[ 0 ];
            loaded += v[ 0 ] * v[ 1 ];
        } );

        percent = total ? loaded / total : 0;

        spans.eq( 0 ).text( Math.round( percent * 100 ) + '%' );
        spans.eq( 1 ).css( 'width', Math.round( percent * 100 ) + '%' );
        updateStatus3();
    }

    function updateStatus3() {
        var text = '', stats;

        if ( state3 === 'ready' ) {
            text = '选中' + fileCount3 + '张图片，共' +
                    WebUploader.formatSize( fileSize3 ) + '。';
        } else if ( state3 === 'confirm' ) {
            stats = uploader2.getStats();
            if ( stats.uploadFailNum ) {
                text = '已成功上传' + stats.successNum+ '张照片至XX相册，'+
                    stats.uploadFailNum + '张照片上传失败，<a class="retry" href="#">重新上传</a>失败图片或<a class="ignore" href="#">忽略</a>'
            }

        } else {
            stats = uploader2.getStats();
            text = '共' + fileCount3 + '张（' +
                    WebUploader.formatSize( fileSize3 )  +
                    '），已上传' + stats.successNum + '张';

            if ( stats.uploadFailNum ) {
                text += '，失败' + stats.uploadFailNum + '张';
            }
        }

        $info3.html( text );
    }

    function setState3( val ) {
        var file, stats;

        if ( val === state3 ) {
            return;
        }

        $upload3.removeClass( 'state-' + state3 );
        $upload3.addClass( 'state-' + val );
        state3 = val;

        switch ( state3 ) {
            case 'pedding':
                $placeHolder3.removeClass( 'element-invisible' );
                $queue3.parent().removeClass('filled');
                $queue3.hide();
                //$statusBar.addClass( 'element-invisible' );
                uploader2.refresh();
                break;

            case 'ready':
                $placeHolder3.addClass( 'element-invisible' );
                $( '#filePicker3' ).removeClass( 'element-invisible');
                $queue3.parent().addClass('filled');
                $queue3.show();
                $statusBar3.removeClass('element-invisible');
                uploader2.refresh();
                break;

            case 'uploading':
                $( '#filePicker3' ).addClass( 'element-invisible' );
                $progress3.show();
                $upload3.text( '暂停上传' );
                break;

            case 'paused':
                $progress3.show();
                $upload3.text( '继续上传' );
                break;

            case 'confirm':
                $progress3.hide();
                $upload3.text( '开始上传' ).addClass( 'disabled' );

                stats = uploader2.getStats();
                if ( stats.successNum && !stats.uploadFailNum ) {
                    setState3( 'finish' );
                    return;
                }
                break;
            case 'finish':
                stats = uploader2.getStats();
                if ( stats.successNum ) {
                    //alert( '上传成功' );
                } else {
                    // 没有成功的图片，重设
                    state3 = 'done';
                    location.reload();
                }
                break;
        }

        updateStatus3();
    }

    uploader2.onUploadProgress = function( file, percentage ) {
        var $li = $('#'+file.id),
            $percent = $li.find('.progress3 span');

        $percent.css( 'width', percentage * 100 + '%' );
        percentages3[ file.id ][ 1 ] = percentage;
        updateTotalProgress3();
    };

    uploader2.onFileQueued = function( file ) {
        fileCount3++;
        fileSize3 += file.size;
        if ( fileCount3 ===1 ) {
            $placeHolder3.addClass( 'element-invisible' );
            $statusBar3.show();
        }
        
        addFile3( file );
        setState3( 'ready' );
        updateTotalProgress3();
    };

    uploader2.onFileDequeued = function( file ) {
        fileCount3--;
        fileSize3 -= file.size;

        if ( !fileCount3 ) {
            setState3( 'pedding' );
        }

        removeFile3( file );
        updateTotalProgress3();

    };

    uploader2.on( 'all', function( type ) {
        var stats;
        switch( type ) {
            case 'uploadFinished':
                setState3( 'confirm' );
                break;

            case 'startUpload':
                setState3( 'uploading' );
                break;

            case 'stopUpload':
                setState3( 'paused' );
                break;

        }
    });

    uploader2.onError = function( code ) {
        if("F_DUPLICATE"==code){
            layer.msg("图片重复！")
        }else{
            layer.msg( 'Eroor: ' + code );
        }
    };

    $upload3.on('click', function() {
        if ( $(this).hasClass( 'disabled' ) ) {
            return false;
        }

        if ( state3 === 'ready' ) {
            uploader2.upload();
        } else if ( state3 === 'paused' ) {
            uploader2.upload();
        } else if ( state3 === 'uploading' ) {
            uploader2.stop();
        }
    });

    $info3.on( 'click', '.retry', function() {
        uploader2.retry();
    } );
    $info3.on( 'click', '.ignore', function() {
        alert( 'todo' );
    } );

    $upload3.addClass( 'state-' + state3 );
    updateTotalProgress3();
});

function delectFile3(id,obj){
    layer.alert("确定删除该图片？", {
        time: 0 //不自动关闭
        ,btn: ['确定', '取消']
        ,yes: function(index){
            layer.close(index);
            $.ajax({
                type:'GET',
                url:'../../../fileHandle/delectFile?id='+id,
                async:false,
                success:function(data){
                    if(data=="SUCCESS"){
                        obj.parentNode.parentNode.remove();
                    }
                },error:function(){
                    alert("删除失败！");
                    return;
                }
            });
        }
    });
}